//@author A0086393U
package rightnow.ui;

import javafx.stage.Stage;

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.NativeInputEvent;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

/**
 * This class implements the global hotkeys necessary to bring up and hide
 * rightNOW without rightNOW having focus. Uses the JNativeHook library.
 */
public class GlobalHotKeys implements NativeKeyListener {
	private Stage stageToMaxiMin;
	
	/* Define global hotkey commands */
	// CTRL+SHIFT+. = maximize/minimize
	private static int hkMaxiMinMods = NativeInputEvent.CTRL_MASK + 
			NativeInputEvent.SHIFT_MASK;
	private static int hkMaxiMinCode = '.';
	
	/**
	 * Registers a native hook in the system and adds this as a listener. 
	 * @throws NativeHookException If a native hook cannot be registered.
	 */
	protected GlobalHotKeys() throws NativeHookException {
		GlobalScreen.registerNativeHook();
		GlobalScreen.getInstance().addNativeKeyListener(this);;
	}

	/**
	 * Unregisters the hook from the system.
	 */
	protected void release() {
		GlobalScreen.unregisterNativeHook();
	}

	@Override
	public void nativeKeyPressed(NativeKeyEvent e) {
		// Do nothing
	}

	@Override
	public void nativeKeyReleased(NativeKeyEvent e) {
		// Do nothing
		/* For debugging, displays the input recorded by JNativeHook: */
		// displayEventInfo(e);
	}

	/**
	 * Checks if the keys pressed are the combination for the maximin of rightNOW,
	 * then performs the action if it is.
	 */
	@Override
	public void nativeKeyTyped(NativeKeyEvent e) {
		// Maximize or minimize hotkey
		if (e.getModifiers() == hkMaxiMinMods && e.getKeyChar() == hkMaxiMinCode) {
			if (stageToMaxiMin.isIconified()) {
				stageToMaxiMin.setIconified(false);
			} else {
				stageToMaxiMin.setIconified(true);
			}
		}
	}
	
	/* Getters and setters */
	protected Stage getStageToMaxiMin() {
		return stageToMaxiMin;
	}

	protected void setStageToMaxiMin(Stage stage) {
		this.stageToMaxiMin = stage;
	}

	// Debug method to print input recorded by JNativeHook
/*private void displayEventInfo(final NativeInputEvent e) {
		System.out.println(e.paramString());
	}
*/
}
